package com.ktwlsoft.archivemanage.domain.business.businessService;

import com.ktwlsoft.archivemanage.domain.dao.entity.App;
import com.ktwlsoft.archivemanage.domain.dao.entity.SysConfig;
import com.ktwlsoft.archivemanage.payload.Result;
import com.ktwlsoft.archivemanage.payload.ResultType;
import org.springframework.stereotype.Service;
import com.ktwlsoft.archivemanage.payload.sysConfig.SysConfigUpdateRequest;
import com.ktwlsoft.archivemanage.domain.dao.repository.SysConfigMapper;
import com.ktwlsoft.archivemanage.domain.dao.repository.AppMapper;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author JokerMo
 * @version 1.0
 * @date 2020/3/12 16:05
 */
@Service
public class SysConfigService {
    /**
     * 数据权限mapper
     */
    private final SysConfigMapper sysConfigMapper;

    private final AppMapper appMapper;

    public SysConfigService(SysConfigMapper sysConfigMapper, AppMapper appMapper) {
        this.sysConfigMapper = sysConfigMapper;
        this.appMapper = appMapper;
    }

    /**
     * 添加数据权限配置
     *
     * @return
     */
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public Result<?> save(SysConfig sysConfig) {
        try {
            sysConfigMapper.insert(sysConfig);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.body(null, ResultType.SAVING_ERROR);
        }
        return Result.ok(sysConfig.getId());
    }

    /**
     * 更行数据权限配置
     *
     * @return
     */
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public Result<?> update(SysConfigUpdateRequest request) {
        SysConfig sysConfig = sysConfigMapper.selectByPrimaryKey(request.getId());
        if (sysConfig == null) {
            return Result.body(null, ResultType.UPDATE_ERROR).withMessage("配置项不存在");
        }
        sysConfig.setEnable(request.getEnable());
        try {
            sysConfigMapper.updateByPrimaryKey(sysConfig);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.body(null, ResultType.SAVING_ERROR);
        }
        return Result.ok(sysConfig.getId());
    }

    /**
     * 获取数据权限配置
     *
     * @return
     */
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public Result<?> getSysConfig() {
        List<SysConfig> sysConfigList = sysConfigMapper.selectAll();
        return Result.ok(sysConfigList);
    }

    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public Result<?> appUpdate(Integer versionNum) {
        App app = appMapper.selectByPrimaryKey(1);
        return Result.ok(app);
    }
}